﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Utilities;
using System.Xml;
using System.Collections;
using Microsoft.Build.Framework;
using System.IO;
using Microsoft.VisualStudio.SourceSafe.Interop;

namespace CTask
{
    public class MyTask:Task
    {
        [Required]
        public string BuildState { get; set; }

        [Required]
        public string BuildConfig { get; set; }

        [Required]
        public string TargetDir { get; set; }

        [Required]
        public string TargetFileName { get; set; }

        [Required]
        public string CommonLibPath { get; set; }

        public override bool Execute()
        {
            #region backup code
            //string dllPath = CopyFromPath.ToString();
            //string toPath = CopyToPath.ToString();
            //if (Directory.Exists(@dllPath))
            //{
            //    if (!Directory.Exists(@toPath))
            //    {
            //        Directory.CreateDirectory(@toPath);
            //    }
            //    string[] filesName = Directory.GetFiles(dllPath);
            //    foreach (string name in filesName)
            //    {
            //        string toCopyName = string.Format("{0}\\{1}", @toPath,name.Substring(name.LastIndexOf("\\")));
            //        if (File.GetLastWriteTime(name) > File.GetLastWriteTime(toCopyName) && name != "CTask.dll")
            //        {
            //            File.Copy(name, toCopyName, true);
            //        }
            //    }
            //}
            #endregion
            //Console.WriteLine("Status:" + BuildConfig);
            if (BuildConfig == "Release")
            {
                if (BuildState == "BeforeBuild")
                {
                    BeforeBuild();
                }
                else
                {
                    AfterBuild();
                }
            }
            else if (BuildConfig == "AutoDebug")
            {
                if (BuildState == "BeforeBuild")
                {
                    GetCodeByVss();
                }
            }
            return true;
        }

        private void BeforeBuild()
        {
            VSSDatabase vssDatabase = new VSSDatabase();
            vssDatabase.Open(Setting.VSSServer, Setting.VSSUser, Setting.VSSPwd);
            VSSItem vssitem = vssDatabase.get_VSSItem(Setting.VSSServerPath, false);
            VSSItem vssitemVersion = null;
            foreach (VSSItem item in vssitem.get_Items(false))
            {
                //item.Type=0:项目文件夹  item.Type=1:项目文件
                if (item.get_Version(item.VersionNumber).Name == TargetFileName)
                {
                    vssitemVersion = item.get_Version(item.VersionNumber);
                }
            }
            if (vssitemVersion != null)
            {
                //由于长时间签出后，再签入会报错（无效的 OLEVERB 结构），所以操作前重新签出一次。
                if (vssitemVersion.IsCheckedOut == 2)
                {
                    vssitemVersion.UndoCheckout(TargetDir + TargetFileName, 0);
                }
                else if (vssitemVersion.IsCheckedOut == 1)
                {
                    throw new Exception("程序集被签出，VSS签入失败!!!!!！");
                }
                vssitemVersion.Checkout(string.Empty, TargetDir + TargetFileName, 0);
            }
        }

        private void AfterBuild()
        {
            VSSDatabase vssDatabase = new VSSDatabase();
            vssDatabase.Open(Setting.VSSServer, Setting.VSSUser, Setting.VSSPwd);
            VSSItem vssitem = vssDatabase.get_VSSItem(Setting.VSSServerPath, false);
            VSSItem vssitemVersion = null;
            foreach (VSSItem item in vssitem.get_Items(false))
            {
                //item.Type=0:项目文件夹  item.Type=1:项目文件
                if (item.get_Version(item.VersionNumber).Name == TargetFileName)
                {
                    vssitemVersion = item.get_Version(item.VersionNumber);
                }
            }
            if (vssitemVersion != null)
            {
                //vssitemVersion.IsCheckedOut=1:被别人签出   vssitemVersion.IsCheckedOut=2:被自己签出
                if (vssitemVersion.IsCheckedOut == 2)
                {
                    vssitemVersion.Checkin(System.Net.Dns.GetHostName(), TargetDir + TargetFileName, 0);
                }
                else if (vssitemVersion.IsCheckedOut == 1)
                {
                    throw new Exception("程序集被签出，VSS签入失败!!!!!！");
                }
            }
            else
            {
                //Console.WriteLine(TargetDir + TargetFileName + "\n\r" + System.Net.Dns.GetHostName());
                vssitem.Add(TargetDir + TargetFileName, System.Net.Dns.GetHostName(), 0);
            }
            //vssitemVersion.Checkout("waiting", TargetDir + TargetFileName, 0);
        }

        private void GetCodeByVss()
        {
            VSSDatabase vssDatabase = new VSSDatabase();
            vssDatabase.Open(Setting.VSSServer, Setting.VSSUser, Setting.VSSPwd);
            VSSItem vssitem = vssDatabase.get_VSSItem(Setting.VSSServerPath, false);
            VSSItem vssitemVersion = null;
            //当文件非只读属性时候，则无法正常获取最新代码。
            foreach (VSSItem item in vssitem.get_Items(false))
            {
                //item.Type=0:项目文件夹  item.Type=1:项目文件
                vssitemVersion = item.get_Version(item.VersionNumber);
                string localPath = CommonLibPath + "\\" + vssitemVersion.Name;
                vssitemVersion.Get(ref localPath, 0);
            }
        }
    }
}
